package com.zhentao.filter;


import com.zhentao.config.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 先获取 request \ response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        log.info("path {}", path);
        // 判断是否登录
        if (path.contains("/login")) {
            log.info("登录请求");
            return chain.filter(exchange);
        }
        // 获取前端的token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            log.error("token 不存在");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 终止过滤器
            return response.setComplete();
        }
        // 判断token 是否有效
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int resilt = AppJwtUtil.verifyToken(claimsBody);
            if (resilt == 1 || resilt == 2) {
                //  token 不合法
                log.error("token 不合法");
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                // 终止过滤器
                return response.setComplete();
            }
            // 获取token中的id
            Object id = claimsBody.get("id");
            // 把id放入到header
            request.mutate().headers(header -> header.add("userId", id + ""));
            // 更新request 放回请求
            exchange.mutate().request(request).build();


        } catch (Exception e) {
            e.printStackTrace();
            // token 不合法
            log.error("token 不合法");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 终止过滤器
            return response.setComplete();
        }
        // 放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}